package com.tinckay.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tinckay.common.annotation.Log;
import com.tinckay.common.constant.ProjectConstant;
import com.tinckay.common.util.LocalDateTimeUtils;
import com.tinckay.entity.form.StorehousePlanForm;
import com.tinckay.entity.po.Role;
import com.tinckay.entity.po.Storehouse;
import com.tinckay.entity.po.StorehousePlan;
import com.tinckay.entity.po.Task;
import com.tinckay.service.StorehousePlanService;
import com.tinckay.service.TaskService;
import io.swagger.annotations.*;
import org.apache.catalina.LifecycleState;
import cn.hutool.core.util.StrUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 仓体浇筑计划 前端控制器
 * </p>
 *
 * @author Jean
 * @since 2018-11-06
 */
@Api(tags = "浇筑计划管理")
@RestController
@RequestMapping("/storehousePlan")
public class StorehousePlanController extends ApiController {

    @Autowired
    private StorehousePlanService storehousePlanService;
    @Autowired
    private TaskService taskService;


    @Log("现场添加浇筑计划")
    @PostMapping("/buildStorehousePlan")
    @ApiOperation("现场添加浇筑计划")
    //@RequiresPermissions("storehousePlan:buildStorehousePlan")
    //@ApiImplicitParams({
    //        @ApiImplicitParam(name = "type", value = "仓体模型类型", required = true, dataType = "int", paramType = "query"),
    //        @ApiImplicitParam(name = "length", value = "仓体【长】", required = true, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "width", value = "仓体【宽】", required = true, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "leftWidth", value = "仓体【左宽】", required = false, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "height", value = "仓体【左高】", required = true, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "rightHeight", value = "仓体【右高】", required = false, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "ventHeight", value = "排气孔高度", required = false, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "limitHeight", value = "变速高度", required = true, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "stopHeight", value = "停止高度", required = true, dataType = "double", paramType = "query"),
    //        @ApiImplicitParam(name = "pipeCode", value = "所属管节编码", required = false, dataType = "String", paramType = "query", defaultValue = "GJ-001"),
    //        @ApiImplicitParam(name = "pumpCode", value = "泵车编码", required = false, dataType = "String", paramType = "query", defaultValue = "PUMP-001")
    //})
    //@RequestParam(value = "type") int type,
    //@RequestParam(value = "length") double length,
    //@RequestParam(value = "width") double width,
    //@RequestParam(required = false) double leftWidth,
    //@RequestParam(value = "leftHeight") double height,
    //@RequestParam(required = false) double rightHeight,
    //@RequestParam(required = false) double ventHeight,
    //@RequestParam(value = "limitHeight") double limitHeight,
    //@RequestParam(value = "stopHeight") double stopHeight,
    //@RequestParam(defaultValue = "GJ-001") String pumpCode,
    //@RequestParam(defaultValue = "PUMP-001") String pipeCode
    public R buildStorehousePan(@RequestBody @Validated StorehousePlanForm form) {

        double heightMin = 0.15;
        double otherMin = 0.5;
        double var1 = 0.1;
        double var2 = 0.3;

        if (heightMin > form.getHeight()) {
            return failed("仓体【高】不能小于：" + heightMin + "(m)");
        }
        if (form.getHeight() > ProjectConstant.MAX_HEIGHT) {
            return failed("仓体【高】不能大于最大测高：" + ProjectConstant.MAX_HEIGHT + "(m)");

        }
        if (otherMin > form.getWidth()) {
            return failed("仓体【宽】不能小于：" + otherMin + "(m)");
        }
        if (otherMin > form.getLength()) {
            return failed("仓体【长】不能小于：" + otherMin + "(m)");
        }
        if (var1 >= form.getLimitHeight() || form.getLimitHeight() > form.getHeight() - var1) {
            return failed("变速高度输入有误");
        }
        if (form.getHeight() + var2 < form.getStopHeight()) {
            return failed("停止高度有误");
        }
        if (form.getType() != 0) {
            if (form.getRightHeight() == null) {
                return failed("右高不能为空");
            }
            if (form.getRightHeight() <= form.getHeight()) {
                return failed("此仓体类型，右高需大于左高");
            }
        }
        StorehousePlan storehousePlan = storehousePlanService.buildStorehousePan(form);
        return success(storehousePlan);
    }

    @Log("删除浇筑计划信息")
    @DeleteMapping
    @ApiOperation("删除浇筑计划信息")
    //@RequiresPermissions("storehousePlan:delete")
    public R delete(@ApiParam("浇筑计划信息id数组") @RequestParam Integer id) {
        storehousePlanService.removeById(id);
        return success(null);
    }

    @Log("新增浇筑计划信息")
    @PostMapping
    @ApiOperation("新增浇筑计划信息")
    //@RequiresPermissions("storehousePlan:add")
    public R add(@RequestBody @Validated(ProjectConstant.Save.class) StorehousePlan storehousePlan) {
        return success(storehousePlanService.save(storehousePlan));
    }

    @Log("更新浇筑计划信息")
    @PutMapping
    @ApiOperation("更新浇筑计划信息")
    //@RequiresPermissions("storehousePlan:update")
    public R update(@RequestBody @Validated(ProjectConstant.Update.class) StorehousePlan storehousePlan) {
        storehousePlanService.updateById(storehousePlan);
        return success(storehousePlan);
    }

    @GetMapping("/list")
    @ApiOperation("历史信息列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "barnNo", value = "仓体编号", defaultValue = "", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pumpCode", value = "泵车编号", defaultValue = "", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "planTime", value = "计划浇筑日期", defaultValue = "", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "storeState", value = "浇筑仓体状态 ", defaultValue = "", required = false, dataType = "int", paramType = "query")
    })
    //@RequiresPermissions("storehousePlan:list")
    public R list(@RequestParam(required = false) String barnNo,
                  @RequestParam(required = false) String pumpCode,
                  @RequestParam(value = "planTime") String planTime,
                  @RequestParam(required = false) Integer storeState) {

        List<StorehousePlan> result = storehousePlanService.findList(barnNo, pumpCode, planTime, storeState);
        return success(result);
    }

    @GetMapping("/page")
    @ApiOperation("分页列表查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "barnNo", value = "仓体编号", defaultValue = "", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pumpCode", value = "泵车编号", defaultValue = "", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "planTime", value = "计划浇筑日期", defaultValue = "", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "storeState", value = "浇筑仓体状态 ", defaultValue = "", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页号", defaultValue = "", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "每页显示数", defaultValue = "", required = false, dataType = "int", paramType = "query")
    })
    //@RequiresPermissions("storehousePlan:page")
    public R page(@RequestParam(required = false) String barnNo,
                  @RequestParam(required = false) String pumpCode,
                  @RequestParam(required = false) String planTime,
                  @RequestParam(required = false) Integer storeState,
                  @RequestParam(defaultValue = "1") int current,
                  @RequestParam(defaultValue = "10") int size) {
        if (StrUtil.isNotBlank(planTime)) {
            try {
                LocalDateTimeUtils.formatDate(planTime);
            } catch (Exception e) {
                return failed("计划浇筑日期格式有误");
            }
        }
        LambdaQueryWrapper<StorehousePlan> wrapper = new QueryWrapper<StorehousePlan>()
                .lambda()
                .eq(StrUtil.isNotBlank(barnNo), StorehousePlan::getStoreCode, barnNo)
                .eq(StrUtil.isNotBlank(pumpCode), StorehousePlan::getPumpCode, pumpCode)
                .eq(storeState != null, StorehousePlan::getStoreState, storeState)
                .likeRight(StrUtil.isNotBlank(planTime), StorehousePlan::getPlanTime, planTime)
                .orderByDesc(StorehousePlan::getPlanTime);
        IPage<StorehousePlan> page = storehousePlanService.page(new Page<>(current, size), wrapper);
        return success(page);
    }

    @GetMapping("/info/{storeCode}")
    @ApiOperation("获取浇筑计划信息")
    //@RequiresPermissions("storehousePlan:info")
    public R info(@PathVariable("storeCode") String storeCode) {
        StorehousePlan storehousePlan = storehousePlanService.storehousePlanInfo(storeCode);
        if (null == storehousePlan) {
            return failed("该仓体没有对应的浇筑计划");
        }
        int stopFlag = 100;
        if (stopFlag != storehousePlan.getStoreState()) {
            storehousePlan.setTransportTask(taskService.list(new QueryWrapper<Task>().lambda().eq(Task::getBarnNo, storeCode)));
        }
        return success(storehousePlan);
    }

    @PutMapping("/changePourNo")
    @ApiOperation("排序编号")
    //@RequiresPermissions("storehousePlan:changePourNo")
    public R changePourNo(@RequestParam("planId") long planId,
                          @RequestParam("pourNo") int pourNo) {
        storehousePlanService.changePourNo(planId, pourNo);
        return success(null);
    }

    @GetMapping("/count")
    @ApiOperation("浇筑计划,阶段耗时统计（单位：s）")
    //@RequiresPermissions("storehousePlan:count")
    public R count(@RequestParam("storeCodes") String[] storeCodes) {
        List<Map<String, Object>> result = storehousePlanService.countPlan(CollectionUtil.toList(storeCodes));
        return success(result);
    }

    @GetMapping("/statistical")
    @ApiOperation("按年月日统计已完成浇筑浇筑计划信息 1日 2月 3年")
    //@RequiresPermissions("storehousePlan:statistical")
    public R statistical(@RequestParam("flag") int flag,
                         @RequestParam("startPlanTime") String startPlanTime,
                         @RequestParam(required = false) String endPlanTime) {
        try {
            LocalDateTimeUtils.formatDate(startPlanTime);
        } catch (Exception e) {
            return failed("起始时间有误");
        }
        List<Map<String, Object>> result = storehousePlanService.statistical(flag, startPlanTime, endPlanTime);
        return success(result);
    }

}

